<template >
  <div class="add-role" style="width: 100%">
    <header style="background-color: rgb(206, 202, 202)">
      <div class="clearfix return-addroles">
        <div class="leftfix clearfix">
          <div class="leftfix icon"><i class="el-icon-back"></i></div>
          <div class="leftfix return">
            
            <span @click="$router.back()" style="cursor:pointer">返回</span>
            
          </div>
          <div class="leftfix gg">|</div>
          <div class="leftfix addroles">{{ roleId ? "编辑角色" : "添加角色"}}</div>
        </div>
        <div class="rightfix admin">黑马管理员</div>
      </div>
    </header>

    <div class="step-container" style="height: 350px;">
      
    <el-steps direction="vertical" :active="activeStep">
    <el-step title="角色信息" description="角色信息填充"></el-step>
    <el-step title="权限信息" description="检查权限是否选择完成"></el-step>
    <el-step title="检查并完成" description="展示已选择权限列表"></el-step>
  </el-steps>
    </div>

    <div
      v-show="activeStep === 1"
      class="form-container"
      style="font-size: 20px;background-color: #e6e8ec;"
    >
      <div class="title" style="font-size: 20px;border-left: 2px solid blue; padding: 8px" >角色信息</div>
      <div class="form" >
        <el-form 
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item
            style="margin-top: 30px"
            label="角色名称 "
            prop="roleName"
            label-position="left"
            label-width=""
          >
            <el-input v-model="roleForm.roleName"></el-input>
          </el-form-item>

          <el-form-item label="角色描述:" style="margin-top: 50px">
            <el-input type="textarea" v-model="roleForm.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div v-show="activeStep === 2" class="form-container1">
      <div class="title" style="font-size: 20px;border-left: 2px solid blue; padding: 8px">权限配置</div>
      <div class="tree-wrapper" style="">
        <div v-for="item in treeList" :key="item.id" class="tree-item" style="font-size: large;width: 200px;">
          <div class="tree-title" style="font-size: large;">{{ item.title }}</div>
          <el-tree
            ref="tree"
            :data="item.children"
            show-checkbox
            :default-expand-all="true"
            node-key="id"
            highlight-current
            :props="{ label: 'title' }"
          />
        </div>
      </div>
    </div>

    <div v-show="activeStep === 3" class="form-container2">
      <div class="title" style="font-size: 20px;border-left: 2px solid blue; padding: 8px">
        检查并完成
      </div>
      <div class="form">
        <div class="info" style="width: 100%">
          <div class="form-item" style="color: #909399">
            角色名称：{{ roleForm.roleName }}
          </div>
          <br />
          <div class="form-item" style="color: #909399">
            角色描述：{{ roleForm.remark }}
          </div>
          <br />
          <div class="form-item" style="color: #909399">角色权限：</div>
          <br />
          <div class="tree-wrapper" >
            <div
              v-for="item in disableTreeList"
              :key="item.id"
              class="tree-item"
              style="padding: 20px"
            >
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="tree1"
                :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                :highlight-current="false"
                :props="{ label: 'title' }"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="btn-container" style="width: 100%">
      <el-button v-if="activeStep > 1" @click="decreseStep">上一步</el-button>
      <el-button v-if="activeStep < 3" type="primary" @click="nextStep" 
        >下一步</el-button
      >
      <el-button v-if="activeStep === 3" type="primary" @click="confirmAdd"
        >{{ conName }}</el-button
      >
    </div>
  </div>
</template>
  <script>
import { getTreeListAPI, createRoleUserAPI,getRoleDetailAPI,updateRoleAPI } from "@/api/role";
export default {
  data() {
    return {
      activeStep: 1,
      conName:'确定添加',
      treeList: [], // 权限树形列表
      disableTreeList: [], // 禁用的tree列表
      diabledTree: [],
      roleForm: {
        roleName: "",
        remark: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输角色名称!", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
  roleId() {
    return this.$route.query.id
  }
},
async mounted() {
    // 在初始化时候就加载好
    console.log("yyyyyyyyyyyyy");
    await this.getTreeList();
    if (this.$route.query.id) {
    this.getRoleDetail()
  }

  },
  methods: {
  // 回填数据
    async getRoleDetail() {
      this.conName = '确定编辑'
      const res = await getRoleDetailAPI(this.roleId)
      const { perms, remark, roleId, roleName } = res.data
      // 回填基础表单
      this.roleForm = { perms, remark, roleId, roleName }
      // 回填Tree
      console.log(this.$refs.tree,"YYYYYYYYYYYYYYYY");
      await this.$refs.tree.forEach((tree, index) => {
        tree.setCheckedKeys(this.roleForm.perms[index])
        console.log(tree.setCheckedKeys(this.roleForm.perms[index]),99991111111111);
        // tree.getCheckedKeys()
      })
      console.log(this.roleForm,"0101010101010101011010");
    },

    async confirmAdd() {
      if (this.roleId) {
         updateRoleAPI(this.roleForm)
      } else {
        // 添加
        await createRoleUserAPI(
          this.roleForm
        )
      }
      this.$message({
        type: 'success',
        message: `${this.roleId ? '编辑' : '新增'}角色成功`
      })
      
      this.$router.back()
    },

    addDisabled(newtreeList) {
      // console.log("进到addDisabled外部")
      // console.log("哈哈哈哈");
      // console.log(newtreeList,"jjjjjjjjjjjjjjjjjj");
      newtreeList.forEach((item) => {
        // console.log("进到addDisabled内部")
        item.disabled = true;
        // 递归处理
        if (item.children && item.children.length > 0) {
          this.addDisabled(item.children);
        }
      })
      // console.log(newtreeList,"hhhhhhhhhh")
      this.disableTreeList = newtreeList
      // console.log(this.disableTreeList,"XXXXXXXXXXXXXXX");
    },

    // 下一步
    nextStep() {
      if (this.activeStep === 3) return;
      if (this.activeStep === 1) {
        // 当前是角色信息状态
        this.$refs.roleForm.validate((ok) => {
          if (ok) {
            this.activeStep++;
          }
        });
      } else if (this.activeStep === 2) {
        // 当前是权限信息状态
        this.roleForm.perms = [];
        this.$refs.tree.forEach((tree) => {
          this.roleForm.perms.push(tree.getCheckedKeys())
          // console.log(888888888,this.roleForm.perms.push(tree.getCheckedKeys()));
        });
        // 如果长度为零 没有选中任何东西
        if (this.roleForm.perms.flat().length === 0) {
          this.$message({
            type: "error",
            message: "请至少选择一个权限点",
          });
        } else {
          // 如果长度不为零，进入到检查并完成
          this.activeStep++;
          console.log("即将进入nextTick")
          this.$nextTick(() => {
            // 回填已选择数据
          console.log("已进入nextTick")
            console.log(this.$refs.tree1, "pppppppppppppp",this.disableTreeList);
            const treeComponentList = this.$refs.tree1
            // this.$refs.tree.forEach((tree, index) => {
            //   tree.setCheckedKeys(this.roleForm.perms[index]);
            //   console.log(this.roleForm.perms[index],"这里有勾勾吗？");
            // })
            treeComponentList.forEach((tree1, index) => {
                console.log("setCheckedKeys我来了");
                tree1.setCheckedKeys(this.roleForm.perms[index])
              })
          })
        }
      }
    },

    async getTreeList() {
      const res = await getTreeListAPI();
      // 分开管理数据(引用类型 一个地方发生变化另一个地方也变 - 深拷贝)
      this.treeList = res.data;
      this.disabledTreeList = JSON.parse(JSON.stringify(res.data));
      // console.log(this.disabledTreeList,"唐夹爆disabledTreeList");
      // 处理禁用
      this.addDisabled(this.disabledTreeList);
      // console.log(this.disabledTreeList,"pppppppp");
    },
    // 下一步
    increseStep() {
      if (this.activeStep === 3) return;
      if (this.activeStep === 1) {
        // 当前是角色信息状态，进行表单校验
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            // 校验通过才能进入下一个状态
            this.activeStep++;
          }
        });
      }
    },
    decreseStep() {
      if (this.activeStep === 1) return;
      this.activeStep--;
    },
    // increseStep() {
    //   if (this.activeStep === 3) return
    //   this.activeStep++
    // }
  },
};
</script>

<style scoped lang="scss">

.add-role {
  position: relative;
  background-color: #19df4b;
}
.step-container {
  position: absolute;
  top: 95px;
  left: 24px;
}
.elSteps {
  position: relative;
}
.elstep1 {
  top: 30px;
}
.elstep2 {
  top: 40px;
}
.elstep3 {
  top: 50px;
}

.leftfix {
  float: left;
}
.rightfix {
  float: right;
}
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

.return-addroles {
  padding: 0 20px;
}
.return,
.addroles,
.icon,
.gg,
.admin {
  font-size: 23px;
  font-weight: 500;
  height: 64px;
  padding: 0 10px;
  color: #000000d9;
  height: 64px;
  line-height: 64px;
}

.gg {
  color: #e3dfdf;
}
.form-container {
  width: 730px;
  height: 300px;
  border: 1px solid black;
  position: absolute;
  padding: 60px 65px 24px;
  left: 438px;
  top: 120px;
}
.form-container1 {
  width: 730px;
  position: absolute;
  padding: 60px 65px 24px;
  left: 438px;
  top: 120px;
  background-color: white;
}
.form-container2 {
  // width: 600px;
  position: absolute;
  padding: 60px 65px 24px;
  left: 438px;
  top: 120px;
}
.title {
  position: absolute;
  top: 10px;
  left: 10px;
  font-weight: bolder;
}

.btn-container {
  position: absolute;
  top: 750px;
  left: 45%;
}
.tree-wrapper {
  display: flex;
  justify-content: space-between;
  
  .tree-item {
    flex: 1;
    // display: inline-block;
    // max-height: 527px;
   
    border-right: 1px solid #e4e7ec;
    padding: 0px 7px;
    text-align: center;
    .tree-title {
      background: #f5f7fa;
      text-align: center;
      padding: 10px 0;
      margin-bottom: 12px;
    }
    
  }
}
</style>
